<template>
  <div class="com-page">
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <!-- 步骤条控件 -->
      <el-steps
        :space="300"
        :active="activeIndex - 1"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页控件 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <!-- 基本信息开始 -->
          <el-tab-pane label="基本信息" name="1">
            <el-form-item label="活动名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                expand-trigger="hover"
                :options="cateData"
                :props="cateCascaderProps"
                v-model="addForm.goods_cat"
                @change="handleChangeCasc"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 基本信息结束 -->

          <!-- 商品参数开始 -->
          <el-tab-pane label="商品参数" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyParamList"
              :key="index"
            >
              <!-- 复选框组件 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2, index2) in item.attr_vals"
                  :key="index2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数结束 -->

          <!-- 商品属性开始 -->
          <el-tab-pane label="商品属性" name="3">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyParamList"
              :key="index"
            >
              <el-input v-model="item.attr_vals[0]"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性结束 -->

          <!-- 商品图片开始 -->
          <el-tab-pane label="商品图片" name="4">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreviewPic"
              :on-remove="handleRemovePic"
              :file-list="fileList"
              :headers="headersObj"
              :on-success="handleSuccessPic"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品图片结束 -->

          <!-- 商品内容开始 -->
          <el-tab-pane label="商品内容" name="5">
            <quill-editor v-model="content"></quill-editor>
            <div class="addBtn-con">
              <el-button @click="definePost" type="primary">添加商品</el-button>
            </div>
          </el-tab-pane>
          <!-- 商品内容结束 -->
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示图片的对话框 -->
    <el-dialog
      title="图片预览"
      :visible="PicdialogVicisible"
      width="50%"
      :before-close="handleCloseDialog"
    >
      <img :src="previewURL" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { request } from "@/utils";
export default {
  components: {},
  props: {},
  data() {
    return {
      activeIndex: "1",
      // 表单数据
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        attrs: [],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 9, message: "长度在 3 到 9 个字符", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      cateData: [],
      cateCascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyParamList: [],
      onlyParamList: [],
      fileList: [],
      uploadURL: "http://www.ysqorz.top:8888/api/private/v1/upload",
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      PicdialogVicisible: false,
      previewURL: "",
      content: "<h2>I am Example</h2>",
    };
  },
  watch: {},
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length != 3) {
        return 1;
      }
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
    },
  },
  methods: {
    // 获取商品分类
    async getCateData() {
      const { data: ret } = await request.get("categories");
      this.cateData = ret.data;
    },
    // 级联选择器发生改变
    handleChangeCasc() {
      // 判断级联选择器选择的是否为第三级别
      if (this.addForm.goods_cat.length != 3) {
        this.$message.warning("请选择三级分类");
        this.addForm.goods_cat = [];
        return;
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length != 3 && oldActiveName == 1) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    // 获取商品参数
    async getParamData(param) {
      const { data: ret } = await request.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: param,
          },
        }
      );
      ret.data.forEach((element) => {
        element.attr_vals = element.attr_vals.split(",");
      });
      if (param == "many") {
        this.manyParamList = ret.data;
      } else {
        this.onlyParamList = ret.data;
      }
    },

    tabClick() {
      if (this.activeIndex == 2) {
        this.getParamData("many");
      } else if (this.activeIndex == 3) {
        this.getParamData("only");
      }
    },
    // 点击已上传图片的钩子
    handlePreviewPic(file) {
      this.PicdialogVicisible = true;
      this.previewURL =
        "http://www.ysqorz.top:8888/" + file.response.data.tmp_path;
    },
    // 文件列表移除文件的钩子
    handleRemovePic(file) {
      // 删除表单中相关图片的信息数据
      this.addForm.pics = this.addForm.pics.filter((item) => {
        return item.pic != file.response.data.tmp_path;
      });
      console.log(this.addForm.pics);
    },
    // 上传文件成功的钩子函数
    handleSuccessPic(response) {
      console.log(response);
      const picInfo = {
        pic: response.data.tmp_path,
      };
      console.log(picInfo);
      this.addForm.pics.push(picInfo);
      console.log(this.addForm);
    },
    // 关闭对话框
    handleCloseDialog() {
      this.PicdialogVicisible = false;
    },
    // 完成提交
    definePost() {
      this.$refs.addFormRef.validate(async (v) => {
        if (!v) {
          this.$message.error("请输入必要的表单项");
          return;
        }
        let Form = JSON.parse(JSON.stringify(this.addForm));
        console.log(Form);

        Form.goods_cat = Form.goods_cat.join(",");
        console.log(Form);
        console.log(this.onlyParamList);
        console.log(this.manyParamList);
        // 处理动态参数
        this.manyParamList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyParamList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        Form.attrs = this.addForm.attrs;
        console.log(Form);
        await request.post("goods", Form);
        this.$router.push("/goods");
      });
    },
  },
  created() {
    this.getCateData();
  },
  mounted() {},
};
</script>
<style lang="less" scoped>
.el-steps {
  margin: 24px auto;
  justify-content: center;
}
.el-checkbox {
  margin: 0 20px 0 0 !important;
}
.el-tab-pane {
  margin-left: 14px;
}
.addBtn-con {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.ql-editor {
  height: 450px;
}
</style>

<style lang="less">
.ql-editor {
  height: 450px;
}
</style>